/**********************************************************
 * 
 *              Class iniFiles 
 *              ini文件 类
 *              
 *  这个类包含 读取 integer,string,boolean,float,datetime
 *  
 *  以及 写入 integer,string,boolean,float,datetime
 *  
 *  设置 自动保存到文件功能
 *  
 *  FileName 文件名
 *  Section  节名
 *  Key      键名
 *  value    键值
 *  
 *  VERSION 1.0.11
 *  author skymens
 *  Update 2024-11-28
 **********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows;

namespace ini
{
    public class iniFiles
    {
        string _FFileName;      //文件名
        Dictionary<string, Dictionary<string, string>> _data;   //ini配置字典
        bool _auto = false;
        /// <summary>
        /// 创建初始化ini配置文件
        /// </summary>
        /// <param name="FileName">ini文件名</param>
        /// <param name="message">返回信息</param>
        public iniFiles(string FileName, out string message)
        {
            if (FileName == "")
            {
                message = "Error:ini配置文件名不得为空！";
                return;
            }
            int i = FileName.LastIndexOf('.');
            string ps = FileName.Substring(i + 1);
            if (ps != "ini")
            {
                message = "Error:非ini配置文件！";
                return;
            }
            _FFileName = FileName;
            _data = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
            if (!File.Exists(_FFileName))
            {
                message = "Error:配置文件不存在！";
                return;
            }
            message = "message:ini载入成功！";
            LoadFile();
        }

        public string FileName { get { return _FFileName; } }
        /// <summary>
        /// LoadFile 私有函数读取ini文件到字典内
        /// </summary>
        private void LoadFile()
        {
            string tempSection = null;
            foreach (var line in File.ReadAllLines(_FFileName))
            {
                string tempLine = line.Trim();//移除这一行开头和末端的空字符；
                if (string.IsNullOrEmpty(tempLine) || tempLine.StartsWith(";") || tempLine.StartsWith("#"))
                {
                    continue;
                }
                if (tempLine.StartsWith("[") && tempLine.EndsWith("]"))
                {
                    tempSection = tempLine.Substring(1, tempLine.Length - 2).Trim();
                    if (!_data.ContainsKey(tempSection))
                    {
                        _data[tempSection] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                    }
                }
                else if (tempSection != null && tempLine.Contains("="))
                {
                    var keyValue = tempLine.Split(new[] { '=' }, 2);    //将tempLine 字符串拆分为2个字符串；
                    var key = keyValue[0].Trim();
                    var value = keyValue.Length > 1 ? keyValue[1].Trim() : string.Empty;

                    _data[tempSection][key] = value;
                }
            }
        }

        /// <summary>
        /// SectionExists 判断节名是否存在
        /// </summary>
        /// <param name="Secion"></param>
        /// <returns></returns>
        public bool SectionExists(string Secion)
        {
            bool value = false;

            if (_data.ContainsKey(Secion))
            {
                value = true;
            }
            return value;
        }
        /*以下是读取函数*/
        /// <summary>
        /// 读取int类型
        /// </summary>
        /// <param name="Section">节名</param>
        /// <param name="aKey">键名</param>
        /// <param name="Default">默认值</param>
        /// <returns>int</returns>
        public int ReadIntger(string Section, string aKey, int Default)
        {
            int value = Default;
            if (_data.TryGetValue(Section, out var sectionData) && sectionData.TryGetValue(aKey, out var valueData))
            {
                if (!int.TryParse(valueData, out value))
                {
                    value = Default;
                }
            }
            return value;
        }
        /// <summary>
        /// 读取string类型
        /// </summary>
        /// <param name="Section">节名</param>
        /// <param name="aKey">键名</param>
        /// <param name="Default">默认值</param>
        /// <returns>string</returns>
        public string ReadString(string Section, string aKey, string Default)
        {
            string value = null;
            if (_data.TryGetValue(Section,out var sectionData) && sectionData.TryGetValue(aKey,out var rdata))
            {
                if (rdata != "")
                {
                    value = Default;
                }
                else
                {
                    value = rdata;
                }

            }
            return value;
        }
        /// <summary>
        /// 读取Boolean类型
        /// </summary>
        /// <param name="Section">节名</param>
        /// <param name="aKey">键名</param>
        /// <param name="Default">默认值</param>
        /// <returns>boolean</returns>
        public bool ReadBoolean(string Section, string aKey, bool Default)
        {
            bool value = false;
            if (_data.TryGetValue(Section, out var sectionData) && sectionData.TryGetValue(aKey, out var rdata))
            {
                value = Default;
                if (rdata.ToLower() == "true") value = true;
                if (rdata.ToLower() == "false") value = false;
             }

            return value;
        }
        /// <summary>
        /// 读取时间参数
        /// </summary>
        /// <param name="Section">节名</param>
        /// <param name="aKey">键名</param>
        /// <param name="Default">默认值</param>
        /// <returns>返回：DateTime 值</returns>
        public DateTime ReadDate(string Section, string aKey, DateTime Default)
        {
            DateTime value = Default;
            if (_data.TryGetValue(Section,out var SectionData) && SectionData.TryGetValue(aKey,out var dateValue))
            {
                DateTime.TryParse(dateValue,out value);
            }
            return value;
        }

        /// <summary>
        /// 读取float数
        /// </summary>
        /// <param name="Section">节名</param>
        /// <param name="aKey">键名</param>
        /// <param name="Default">默认值</param>
        /// <returns>返回：float 值</returns>
        public float ReadFloat(string Section, string aKey, float Default)
        {
            string floatStr = "";
            float value = Default;

            if (_data.TryGetValue(Section,out var sectionData) && sectionData.TryGetValue(aKey,out floatStr))
            {
                float.TryParse(floatStr, out value);
            }
            return value;
        }
        /*以下是写入函数*/
        public void WriteString(string Section, string aKey, string value)
        {
            if (!_data.ContainsKey(Section))
            {
                _data[Section] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            }
            _data[Section][aKey] = value;
            if (_auto == true)
            {
                Updata();
            }
        }

        public void WriteIntger(string Section, string aKey, int value)
        {
            if (!_data.ContainsKey(Section))
            {
                _data[Section] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            }
            _data[Section][aKey] = value.ToString();
            if (_auto == true)
            {
                Updata();
            }
        }

        public void WriteBoolean(string Section, string aKey, bool value)
        {
            if (!_data.ContainsKey(Section))
            {
                _data[Section] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            }
            _data[Section][aKey] = value.ToString();
            if (_auto == true)
            {
                Updata();
            }
        }

        public void WriteDateTime(string Section, string aKey, DateTime value)
        {
            if (!_data.ContainsKey(Section))
            {
                _data[Section] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            }
            _data[Section][aKey] = value.ToString();
            if (_auto == true)
            {
                Updata();
            }
        }

        public void WriteFloat(string Section, string aKey, float value)
        {
            if (!_data.ContainsKey(Section))
            {
                _data[Section] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            }
            _data[Section][aKey] = value.ToString();
            if (_auto == true)
            {
                Updata();
            }
        }

        private void Updata()
        {
            using (var writer = new StreamWriter(_FFileName))
            {
                foreach (var section in _data)
                {
                    writer.WriteLine($"[{section.Key}]");
                    foreach (var keyValue in section.Value)
                    {
                        writer.WriteLine($"{keyValue.Key}={keyValue.Value}");
                    }
                }
            }
        }
        /// <summary>
        /// 将配置信息保存到配置文件
        /// </summary>
        public void Save()
        {
            Updata();
        }
        /// <summary>
        /// 开启自动保存到文件
        /// </summary>
        /// <param name="auto">boolean型 false 不开启，true 开启自动保存，每次更改ini配置会立即更新ini文件不需要Save命令</param>
        public void AutoSave(bool auto)
        {
            _auto = auto;
        }
    }
}
